use super::{err, err_value, json, ok, ECode, Part, Resp};
use bytes::BufMut;
use calamine::{open_workbook_from_rs, Reader, Xlsx};
use std::io::Cursor;
use tracing::instrument;

#[instrument(skip_all, name = "do_cmd")]
pub async fn do_cmd(part: &mut Part) -> Resp {
    let mut buf = vec![];

    while let Some(v) = part.data().await {
        let tmp = v.or_else(|e| err!(ECode::FileWrite, e))?;
        buf.put(tmp);
    }

    let file = Cursor::new(buf);

    let mut workbook: Xlsx<_> =
        open_workbook_from_rs(file).or_else(|e| err!(ECode::FileRead, e))?;

    let sheet = workbook
        .worksheet_range_at(0)
        .ok_or(err_value(ECode::FileRead, "sheet error"))?
        .or_else(|e| err!(ECode::FileRead, e))?;

    let row = sheet.rows();
    let mut ret = Vec::new();

    for r in row {
        let mut col = Vec::new();
        for c in r {
            col.push(c.to_string());
        }

        ret.push(col);
    }

    ok!(json!(ret))
}
